<template>
	<div class="login-form">
		<el-card shadow="never">
			<!--<el-tabs type="border-card" v-model="tabName" @tab-click="handleCaptcha">-->
				<!--<el-tab-pane :label="$t('login.userLogin')" key="user" name="user">-->
					<el-form ref="loginForm" label-position="top" status-icon :rules="rules" :model="loginForm" size="default" autocomplete="off">
						<!--<el-form-item prop="tenant">-->
							<!--<el-input type="text" v-model="loginForm.tenant" :placeholder="$t('login.tenantCode')" autocomplete="off">-->
								<!--<template slot="prepend"><i class="dzzw-icon-outline icon-stamp" style="font-size:1.5em"></i></template>-->
							<!--</el-input>-->
						<!--</el-form-item>-->
						<el-form-item prop="account">
							<el-input type="text" v-model="loginForm.account" :placeholder="$t('login.username')" autocomplete="off">
								<template slot="prepend"><i class="dzzw-icon-outline icon-user1" style="font-size:1.5em"></i></template>
							</el-input>
						</el-form-item>
						<el-form-item prop="pwd">
							<el-input v-model="loginForm.pwd" :placeholder="$t('login.password')" auto-complete="off" show-password>
								<template slot="prepend"><i class="dzzw-icon-outline icon-password" style="font-size:1.5em"></i></template>
							</el-input>
						</el-form-item>
						<el-form-item prop="code">
							<el-input type="text" v-model="loginForm.code" maxlength="4" placeholder="- - - -" autocomplete="off" @keyup.enter.native="handleLogin">
								<template slot="prepend"><i class="dzzw-icon-outline icon-verification1" style="font-size:1.5em"></i></template>
								<template slot="append">
									<img class="login-code" :src="captcha" @click="handleCaptcha">
								</template>
							</el-input>
						</el-form-item>
						<el-form-item class="remember-pwd">
							<el-checkbox :label="$t('login.remember')" name="rememberPwd" v-model="loginForm.rememberPwd"></el-checkbox>
						</el-form-item>
						<el-button size="default" @click.native.prevent="handleLogin" type="primary" class="button-login">{{$t('login.submit')}}</el-button>
					</el-form>
				<!--</el-tab-pane>-->
				<!--<el-tab-pane :label="$t('login.developerLogin')" key="developer" name="developer">-->
					<!--<el-form ref="developerForm" label-position="top" status-icon :rules="rules" :model="developerForm" size="default" autocomplete="off">-->
						<!--<el-form-item prop="account">-->
							<!--<el-input type="text" v-model="developerForm.account" :placeholder="$t('login.username')" autocomplete="off">-->
								<!--<template slot="prepend"><i class="dzzw-icon-outline icon-user1" style="font-size:1.5em"></i></template>-->
							<!--</el-input>-->
						<!--</el-form-item>-->
						<!--<el-form-item prop="pwd">-->
							<!--<el-input v-model="developerForm.pwd" :placeholder="$t('login.password')" autocomplete="off" show-password>-->
								<!--<template slot="prepend"><i class="dzzw-icon-outline icon-password" style="font-size:1.5em"></i></template>-->
							<!--</el-input>-->
						<!--</el-form-item>-->
						<!--<el-form-item prop="code">-->
							<!--<el-input type="text" v-model="developerForm.code" maxlength="4" placeholder="- - - -" autocomplete="off" @keyup.enter.native="handleLogin">-->
								<!--<template slot="prepend"><i class="dzzw-icon-outline icon-verification1" style="font-size:1.5em"></i></template>-->
								<!--<template slot="append">-->
									<!--<img class="login-code" :src="captcha" @click="handleCaptcha">-->
								<!--</template>-->
							<!--</el-input>-->
						<!--</el-form-item>-->
						<!--<el-form-item class="remember-pwd">-->
							<!--<el-checkbox :label="$t('login.remember')" name="rememberPwd" v-model="developerForm.rememberPwd"></el-checkbox>-->
						<!--</el-form-item>-->
						<!--<el-button size="default" @click.native.prevent="handleLogin" type="primary" class="button-login">{{$t('login.submit')}}</el-button>-->
					<!--</el-form>-->
				<!--</el-tab-pane>-->
			<!--</el-tabs>-->
		</el-card>
		<!--<p class="login-options" v-show="tabName === 'developer'">-->
			<!--<router-link tag="span" to="/forgot">{{$t('login.forget')}}</router-link>-->
			<!--<router-link tag="span" to="/register">{{$t('login.regist')}}</router-link>-->
		<!--</p>-->
	</div>
</template>

<script>
import {mapGetters} from 'vuex'
import Cookies from 'js-cookie'
import {decrypt} from '@/util/crypto'
import { randomLenNum } from "@/util/util";
import { getCaptcha, validCaptcha } from '@/api/captcha'

export default {
    name: 'user-login',
    data() {
            const validImgcode = (rule, value, callback) => {
            const key = this.tabName === 'developer' ? 'developerForm' : 'loginForm';
            validCaptcha(this[key].random, value).then(data => {
                if (!data.success) {
                    callback(new Error('验证码不合法!'))
                    this.handleCaptcha()
                }
                else
                    callback()
            })
            .catch(err => {
                console.log(err)
                callback(new Error('验证失败!'))
                this.handleCaptcha()
            })
        };
        return {
            captcha: '',
            tabName:this.$route.query.tabName || 'user',
            flag: true,
            dvFlag:true,
            // 表单
            loginForm: {
                account: '',
                pwd: '',
                tenant:'',
                rememberPwd:'',
                code: '',
                type: '0',
                random: ''
            },
            developerForm:{
                account: '',
                pwd: '',
                rememberPwd:'',
                code: '',
                type: '1',
                random: ''
            },
            // 校验
            rules: {
                account: [{
                    required: true,
                    message: '请输入登录账号',
                    trigger: 'blur'
                }],
                pwd: [{
                        required: true,
                        message: '请输入登录密码',
                        trigger: 'blur'
                    },
                    {
                        min: 6,
                        message: '密码必须至少为 6 个字符',
                        trigger: "blur"
                    }
                ],
                // tenant: [{
                //     required: true,
                //     message: '请输入租户编码',
                //     trigger: 'blur'
                // }],
                code: [
                    {required: true, message: '请输入图片验证码', trigger: 'blur'},
                    {validator: validImgcode, trigger: 'blur'}
                ]
            }
        };
    },
    computed: {
        ...mapGetters(['secretKey']),
    },
    created() {
        const isCookieName = Cookies.get('ecgap_name')
        if (isCookieName && localStorage.rememberPwd && localStorage.rememberFlag) {
            const psw = decrypt(Cookies.get('ecgap_cipher'),this.secretKey)
            const key = localStorage.rememberFlag === 'developer' ? 'developerForm' : 'loginForm';
            this[key].account = isCookieName;
            this[key].pwd = psw ? psw : ''
            this[key].rememberPwd = true
        }
    },
    mounted() {
        this.handleCaptcha();
    },
    methods: {
        handleLogin() {
            const key = this.tabName === 'developer' ? 'developerForm' : 'loginForm';
            this.$refs[key].validate(valid => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: '登录中,请稍后......',
                        spinner: "el-icon-loading"
                    });
                    this.$store.dispatch('login', this[key]).then(ret => {
                        if (this[key].rememberPwd) {
                            localStorage.rememberPwd = 'true'
                            localStorage.rememberFlag = this.tabName
                        } else{
                            localStorage.rememberPwd && (localStorage.rememberPwd = '',localStorage.rememberFlag = '')
                        }
                        // if (ret.tenantId) {
                            this.$router.push({path: '/dashboard'});
                        // } else {
                        //     this.$router.push({path: '/user'});
                        // }
                    })
                    .catch(err => {
                        this.handleCaptcha()
                        this.$message.error("账号或密码不正确");
                    })
                    .finally(() =>{
                        loading.close();
                    });
                }
            });
        },
        handleCaptcha(){
            const key = this.tabName === 'developer' ? 'developerForm' : 'loginForm';
            this[key].code = ''
            this[key].random = randomLenNum(4, true)
            getCaptcha(this[key].random)
            .then(data => {
                if (data.success) {
                    this.captcha = data.data.captcha
                }
            })
            .catch(err => {
                console.log(err)
                this.$message.error('验证码生成失败')
            })
        }
    }
};
</script>

<style lang="scss">
	@import'~_s/variables';

	.login-form {
		text-align: left;
		.icon-font {
			cursor: pointer;
		}
		.el-card {
			margin-bottom: 15px;
		}
		.button-login {
			width: 100%;
		}
		// 输入框左边的图表区域缩窄
		.el-input-group__prepend {
			padding: 0px 14px;
		}
		.el-input-group__append {
			padding-left: 0;
			padding-right: 0;
			min-width: 120px;
			img {
				cursor: pointer;
			}
		}
		.login-code {
			height: 40px - 2px;
			display: block;
			/*margin: auto;*/
			border-top-right-radius: 2px;
			border-bottom-right-radius: 2px;
			cursor: pointer;
		}
		.el-form {
			.remember-pwd{
				margin-top: -15px;
				margin-bottom: 5px;
			}
		}
		.login-options {
			display: flex;
			justify-content: space-between;
			margin: 0px;
			padding: 0px;
			font-size: 14px;
			color: #409EFF;
			margin-bottom: 15px;
			font-weight: bold;
			cursor: pointer;
		}
	}
</style>
